function loadGradeData() {
    // 调用 API 获取学生数据
    $.ajax({
        url: "http://localhost:8080/grade/list", // 替换为你的API地址
        method: "GET",
        dataType: "json",
        contentType: "application/json",
        cache: false,
        success: function (response) {
            // 清空学生表格数据
            $("#grades-tbody").empty();

            // 遍历后端返回的学生数组
            $.each(response.data, function (index,grade) {
                // 生成表格行 HTML
                let gradeRowHTML = `<tr>
                    <td>${grade.id}</td>
                    <td>${grade.stu_name}</td>
                    <td>${grade.co_name}</td>
                    <td>${grade.grade}</td>                
                    <td>
                    <button class="btn btn-sm btn-primary btn-edit-grade" data-grade-id="${grade.id}">编辑</button>
                    <button class="btn btn-sm btn-danger" data-grade-id="${grade.id}">删除</button>
                    </td>
                    </tr>`;

                // 将表格行添加到表格中
                $("#grades-tbody").append(gradeRowHTML);
            });
        },
        error: function (error) {
            // 如果出现错误，弹出错误消息
            console.error("获取学生数据失败：", error);
        }
    });
}

// 清空成绩输入框
function resetGradeForm() {
    $("#student-name").val("");
    $("#course-name-grade").val("");
    $("#grade").val("");
}

function initializeGradeTable() {
    loadGradeData();

    // 添加成绩
    $("#add-grade-btn").click(function () {
        let studentName = $("#student-name").val();
        let courseName = $("#course-name-grade").val();
        let grade = $("#grade").val();

        if (studentName === "" || courseName === "" || grade === "") {
            alert("输入不能为空！");
            return;
        }

        $.ajax({
            url: "http://localhost:8080/grade/add",
            method: "POST",
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify({
                "stu_name": studentName,
                "co_name": courseName,
                "grade": grade
            }),
            success: function (response) {
                if (response.message === "ok") {
                    alert("成绩添加成功！");
                    resetGradeForm();
                    loadGradeData();
                } else {
                    resetGradeForm()
                    alert("操作失败: " + response.message);
                }
            },
            error: function (error) {
                console.error("添加成绩操作失败：", error);
            }
        });
    });
//删除
    $("#grades-tbody").on("click", ".btn-danger", function () {
        let gradeId = $(this).data("grade-id");

        // 确认是否要删除
        if (!confirm("确定要删除此成绩吗？")) {
            return;
        }

        // 发送 AJAX 请求以删除成绩
        $.ajax({
            url: `http://localhost:8080/grade/delete/${gradeId}`,
            method: "DELETE",
            dataType: "json",
            contentType: "application/json",
            success: function (response) {
                if (response.message === "ok") {
                    alert("成绩删除成功！");
                    loadGradeData();
                } else {
                    alert("操作失败: " + response.message);
                }
            },
            error: function (error) {
                console.error("成绩删除操作失败：", error);
            }
        });
    });

    // 编辑成绩
    $("#grades-tbody").on("click", ".btn-edit-grade", function () {
        // 获取当前行的成绩数据
        let gradeRow = $(this).parent().parent();
        let gradeId = $(this).data("grade-id");
        let studentName = gradeRow.children().eq(1).text();
        let courseName = gradeRow.children().eq(2).text();
        let grade = gradeRow.children().eq(3).text();

        // 在模态框中设置成绩数据
        $('#edit-grade-id').val(gradeId);
        $('#edit-student-name').val(studentName);
        $('#edit-course-name-grade').val(courseName);
        $('#edit-grade').val(grade);

        // 显示模态框
        $('#edit-grade-modal').modal('show');
    });

// 保存编辑后的成绩数据
    $('#saveGradeChangesBtn').click(function () {
        let gradeId = $('#edit-grade-id').val();
        let studentName = $('#edit-student-name').val();
        let courseName = $('#edit-course-name-grade').val();
        let grade = $('#edit-grade').val();

        // 发送更新请求给后端 API
        updateGradeData(gradeId, studentName, courseName, grade);

        // 隐藏模态框
        $('#edit-grade-modal').modal('hide');
    });

    /**
     * 更新成绩数据的函数
     * @param gradeId
     * @param studentName
     * @param courseName
     * @param grade
     */
    function updateGradeData(gradeId, studentName, courseName, grade) {
        // 通过 AJAX 向后端发送更新请求
        $.ajax({
            url: `http://localhost:8080/grade/edit/${gradeId}`,
            method: "PUT",
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify({
                "stu_name": studentName,
                "co_name": courseName,
                "grade": grade
            }),
            cache: false,
            success: function (response) {
                if (response.message === "ok") {
                    alert("更新成功！");
                    // 请求成功，重新加载成绩数据
                    loadGradeData();
                } else {
                    alert("更新失败: " + response.message);
                }
            },
            error: function (error) {
                console.error("更新成绩数据失败：", error);
            }
        });
    }
}

function bindGradeTableEvents() {
    initializeGradeTable();
}
